<?php
/**
 * Created by PhpStorm.
 * User: Shroom Ari
 * Date: 11/21/14
 * Time: 9:43 PM
 */
class News extends MY_Controller {
    public function __construct()
    {
        parent::__construct();
        $this->layout->setLayout('backend/index');
        $session_data = $this->session->userdata('logged_in');
        $usergroup_id = $session_data['usergroup_id'];
        if ($usergroup_id!=1) redirect('../petshop');
    }
    public function listNews($page=1){
        $data['seo']['title']='News';
        $total_news= $this->mnews->countAll();
        $perpage = 5;
        $config['base_url'] = "/petshop/backend/news/listNews/"; // xác định trang phân trang
        $config['total_rows'] = $total_news; // xác định tổng số record
        $config['per_page'] = $perpage; // xác định số record ở mỗi trang
        $config['num_links'] = 10;
        $config['cur_page'] =$page;
        $this->pagination->initialize($config);
        $data['pagination'] = $this->pagination->create_links();
        $data['_config']= $config;
        $data['_page']=$page;
        $offset = ($page-1) * $perpage;
        $data['news']= $this->mnews->getNews($perpage,$offset);
        if (isset($_POST['submit']) and $_POST['submit'] == 'delete'){
            $this->mnews->delete();
        }
        $this->layout->view('backend/layout/news', $data);
    }
    public function newNews(){
        $data['seo']['title']='Add News';
        if (isset($_POST['submit']) and $_POST['submit'] == 'add'){
            $this->form_validation->set_rules('title', 'Title', 'required|min_length[3]|xss_clean|callback__title');
            $this->form_validation->set_rules('content', 'Content', 'required|xss_clean');
            if($this->form_validation->run())
            {
                $data = array(
                    'news_id' =>'',
                    'title' => $this->input->post('title'),
                    'content' => $this->input->post('content'),
                    'url_image' => $this->save_image(),
                    'news_date' => gmdate('Y-m-d')
                );
                if($this->mnews->create($data))
                {
                    redirect('backend/news/listNews');
                }
            }
        }
        $this->layout->view('backend/layout/new_news', $data);

    }

    public function title($title){
        $count=$this->db->where(array('title'=>$title))->from('news')->count_all_results();
        if($count!=0){
            $this->form_validation->set_message('_title','%s is not available');
            return FALSE;
        }
        return TRUE;
    }
    function save_image(){
        $name = substr(str_shuffle("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"), 0, 10).".jpg";

        $allowedExts = array("gif", "jpeg", "jpg", "png");
        $temp = explode(".", $_FILES["file"]["name"]);
        $extension = end($temp);
        if ((($_FILES["file"]["type"] == "image/gif")
                || ($_FILES["file"]["type"] == "image/jpeg")
                || ($_FILES["file"]["type"] == "image/jpg")
                || ($_FILES["file"]["type"] == "image/jpeg")
                || ($_FILES["file"]["type"] == "image/x-png")
                || ($_FILES["file"]["type"] == "image/png"))
            && in_array($extension, $allowedExts)) {
            $file_name = $_SERVER["DOCUMENT_ROOT"]."/petshop/public/images/".$name;
            if(file_exists($file_name)) {
                chmod($file_name,0755); //Change the file permissions if allowed
                unlink($file_name); //remove the file
            }
            if ($_FILES["file"]["error"] > 0) {
                echo "Return Code: " . $_FILES["file"]["error"] . "<br>";
            } else {
                move_uploaded_file($_FILES["file"]["tmp_name"], $file_name);
                echo 1;
            }
        }
        return $name;
    }
    public function delete(){
        $this->mnews->delete($this->input->post('id'));
    }
    public function edit($id){
        $data['seo']['title']='Edit News';
        $data['newsById']= $this->mnews->getNewsById($id);
        if (isset($_POST['submit']) and $_POST['submit'] == 'edit'){
            $this->form_validation->set_rules('title', 'Title', 'required|min_length[3]|xss_clean|callback__title');
            $this->form_validation->set_rules('content', 'Content', 'required|xss_clean');
            if($this->form_validation->run())
            {
                if ($_FILES["file"]["error"] == 0)
                $dt = array(
                    'title' => $this->input->post('title'),
                    'content' => $this->input->post('content'),
                    'url_image' => $this->save_image(),
                    'news_date' => $this->input->post('news_date')
                );
                else
                    $dt = array(
                        'title' => $this->input->post('title'),
                        'content' => $this->input->post('content'),
                        'news_date' => $this->input->post('news_date')
                    );
                if($this->mnews->updateNews($id,$dt))
                {

                    redirect('backend/news/listNews');
                }
            }
        }
        $this->layout->view('backend/layout/edit_news', $data);
    }
}